package com.wlts.wzy.DYGoodsModule.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.DYGoodsModule.DYapi.DySdk;
import com.wlts.wzy.DYUserModule.entity.DyOauth;
import com.wlts.wzy.DYUserModule.entity.DyStoreUser;
import com.wlts.wzy.LMGoodsModule.entity.LmGoods;
import com.wlts.wzy.LMGoodsModule.entity.LmSelfGoods;
import com.wlts.wzy.LMGoodsModule.service.ILmGoodsService;
import com.wlts.wzy.LMGoodsModule.service.ILmSelfGoodsService;
import com.wlts.wzy.Result.Result;
import com.wlts.wzy.api.request.dy.*;
import com.wlts.wzy.api.request.lm.LmDelGoodsToKSRequest;
import com.wlts.wzy.api.response.dy.AddGoodsToDyResponse;
import com.wlts.wzy.api.response.dy.GetShopCategoryDyResponse;
import com.wlts.wzy.api.vo.LmGoodsSkuVO;
import com.wlts.wzy.configBean.DyConfig.DyConfig;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 快手商品类目表 前端控制器
 * </p>
 *
 * @author zhiyong
 * @since 2021-01-31
 */
@Api(tags = "抖音商品 前端控制器")
@RestController
@RequestMapping("/DYGoodsModule")
public class DyGoodsController {
    @Autowired
    private DyConfig dyConfig;
    @Autowired
    private ILmSelfGoodsService lmSelfGoodsService;
    @Autowired
    private ILmGoodsService lmGoodsService;

    @ApiOperation(value = "获得快手分类")
    @RequestMapping(value = "getShopCategoryDy", method = RequestMethod.POST)
    public Result<List<GetShopCategoryDyResponse>> getShopCategoryDy(@RequestBody GetShopCategoryDyRequest request) {

        DyStoreUser dyStoreUser = dyConfig.getDyStoreUserConfig();

        DyOauth dyOauth = dyStoreUser.getDyOauth();

        if (dyOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        List<GetShopCategoryDyResponse> response = DySdk.getDyShopCategory(dyStoreUser.getAppKey(), dyStoreUser.getAppSecret(), dyOauth.getAccessToken(), request);

        return Result.buildResult(response);

    }


    @ApiOperation(value = "推送商品到dy小店")
    @RequestMapping(value = "lmPutGoodsToDy", method = RequestMethod.POST)
    public Result<AddGoodsToDyResponse> lmPutGoodsToDy(@RequestBody LmPutGoodsToDyRequest request) {

        //820140

        DyStoreUser dyStoreUser = dyConfig.getDyStoreUserConfig();

        DyOauth dyOauth = dyStoreUser.getDyOauth();

        if (dyOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        //  LmSelfGoods selfGoodsRequest = new LmSelfGoods();

        //      CopyUtils.copyProperties(request, selfGoodsRequest);

        MyLambdaQueryWrapper<LmSelfGoods> wrapper = new MyLambdaQueryWrapper<>();
        wrapper.eq(LmSelfGoods::getUserUuid, dyStoreUser.getUuid());
        wrapper.eq(LmSelfGoods::getId, request.getId());
        wrapper.eq(BaseEntity::getDelFlag, "0");

        LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(wrapper);

        if (lmSelfGoods == null) {
            return Result.buildResult(500, "商品不存在");
        }
        if (lmSelfGoods.getKsSellStatus() == 1) {
            return Result.buildResult(500, "商品已上架");
        }

        List<LmGoodsSkuVO> lmGoodsSkuVOList = JSONArray.parseArray(request.getSkuList(), LmGoodsSkuVO.class);

        long reItemId = System.currentTimeMillis();

        AddGoodsToDyApiRequest addGoodsToDyApiRequest = new AddGoodsToDyApiRequest();
        addGoodsToDyApiRequest.setOut_product_id(reItemId + "");
        addGoodsToDyApiRequest.setProduct_type(0 + "");
        addGoodsToDyApiRequest.setProduct_format("品牌|");
        addGoodsToDyApiRequest.setName(lmSelfGoods.getItemTitle());
        addGoodsToDyApiRequest.setPic("https:" + lmSelfGoods.getMainPicPrl());

        addGoodsToDyApiRequest.setCategory_leaf_id(request.getCategory_leaf_id());

//        addGoodsToDyApiRequest.setFirst_cid(request.getFirst_cid());
//        addGoodsToDyApiRequest.setSecond_cid(request.getSecond_cid());
//        addGoodsToDyApiRequest.setThird_cid(request.getThird_cid());


        List<String> detailImages = new ArrayList<>();
        LmGoods lmGoods = lmGoodsService.getOne(new MyLambdaQueryWrapper<LmGoods>().eq(BaseEntity::getDelFlag, "0").eq(LmGoods::getItemId, lmSelfGoods.getItemId()));
        if (lmGoods != null) {
            if (StringUtils.isNotEmpty(lmGoods.getPicList())) {
                List<String> strings = JSON.parseArray(lmGoods.getPicList(), String.class);
                strings.forEach(utl -> {
                    if (detailImages.size() < 20) {
                        detailImages.add(utl);
                    }
                });
            }
        }
        if (detailImages.size() > 0) {
            addGoodsToDyApiRequest.setDescription(detailImages.stream().map(String::valueOf).collect(Collectors.joining("|")));
        } else {
            addGoodsToDyApiRequest.setDescription("https:" + lmSelfGoods.getMainPicPrl());

        }

        addGoodsToDyApiRequest.setPay_type("1");
        addGoodsToDyApiRequest.setMarket_price(lmSelfGoods.getReservePrice().toString());
        addGoodsToDyApiRequest.setDiscount_price(lmSelfGoods.getReservePrice().toString());
        addGoodsToDyApiRequest.setFreight_id(request.getExpressTemplateId()+"");
        addGoodsToDyApiRequest.setReduce_type("1");
        addGoodsToDyApiRequest.setDelivery_delay_day("2");
        addGoodsToDyApiRequest.setWeight(request.getWeight());
        addGoodsToDyApiRequest.setWeight_unit("1");
        addGoodsToDyApiRequest.setSupply_7day_return(request.getSupply_7day_return()+"");
        addGoodsToDyApiRequest.setMobile(request.getMobile()+"");
        addGoodsToDyApiRequest.setCommit(request.getCommit()+"");

        String skuImages = lmGoodsSkuVOList.stream().map(LmGoodsSkuVO::getSkuPicUrl).collect(Collectors.joining(","));

        String skuName = lmGoodsSkuVOList.stream().map(LmGoodsSkuVO::getSkuTitle).collect(Collectors.joining(","));

        addGoodsToDyApiRequest.setSpecs("规格|" + skuName);

        addGoodsToDyApiRequest.setSpec_pic(skuImages);


        List<AddGoodsSkuToDyApiRequest> skuList = lmGoodsSkuVOList.stream().map(lmGoodsSkuVO -> {

            AddGoodsSkuToDyApiRequest param = new AddGoodsSkuToDyApiRequest();
            param.setSpec_detail_name1(lmGoodsSkuVO.getSkuTitle());
            param.setStock_num(lmGoodsSkuVO.getStock());
            param.setCode(lmGoodsSkuVO.getSkuId().toString());
            param.setOut_sku_id(lmGoodsSkuVO.getSkuId());
            param.setPrice(lmGoodsSkuVO.getPriceCent());
            addGoodsToDyApiRequest.setDiscount_price(lmGoodsSkuVO.getPriceCent()+"");
            return param;
        }).collect(Collectors.toList());


        addGoodsToDyApiRequest.setSpec_prices(JSON.toJSONString(skuList));


        AddGoodsToDyResponse addGoodsToDyResponse = DySdk.DyAddV2(dyStoreUser.getAppKey(), dyStoreUser.getAppSecret(), dyOauth.getAccessToken(), addGoodsToDyApiRequest);


        if (addGoodsToDyResponse != null) {

            lmSelfGoods.setKsGoods(JSON.toJSONString(addGoodsToDyResponse.getMsg()));

            lmSelfGoods.setKwaiItemId(addGoodsToDyResponse.getProductId());

            lmSelfGoods.setKsSellStatus(1);

            lmSelfGoods.setRelItemId(reItemId);

            lmSelfGoodsService.updateById(lmSelfGoods);

            return Result.buildResult(addGoodsToDyResponse);
        } else {
            return Result.buildResult(500, addGoodsToDyResponse.getMsg());
        }

    }


    @ApiOperation(value = "删除商品抖音平台对应商品")
    @RequestMapping(value = "delLmPutGoodsToDy", method = RequestMethod.POST)
    public Result delLmPutGoodsToDy(@RequestBody LmDelGoodsToKSRequest request) {


        MyLambdaQueryWrapper<LmSelfGoods> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(BaseEntity::getDelFlag, "0");

        wrapper.eq(LmSelfGoods::getKwaiItemId, request.getKwaiItemId());

        wrapper.isNotNull(LmSelfGoods::getKwaiItemId);

        wrapper.eq(LmSelfGoods::getKwaiItemId, request.getKwaiItemId());


        LmSelfGoods lmSelfGoods = lmSelfGoodsService.getOne(wrapper);

        if (lmSelfGoods == null) {
            return Result.buildResult();
        }



        DyStoreUser ksStoreUser = dyConfig.getDyStoreUserConfig();

        DyOauth ksOauth = ksStoreUser.getDyOauth();

        if (ksOauth == null) {
            return Result.buildResult(500, "账号未授权");
        }

        DelGoodsToDyRequest delGoodsToDyRequest=new DelGoodsToDyRequest();

        delGoodsToDyRequest.setProduct_id(request.getKwaiItemId()+"");

        boolean flag = DySdk.productDel(ksStoreUser.getAppKey(), ksStoreUser.getAppSecret(), ksOauth.getAccessToken(), delGoodsToDyRequest);

        if (flag) {

            lmSelfGoods.setKsSellStatus(2);

            lmSelfGoodsService.updateById(lmSelfGoods);

            return Result.buildResult(flag);
        } else {
            return Result.buildResult(500, "删除失败");
        }

    }


}